<?php

/*
	Class: DealersViewDealers

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>

	About: See Also
		- <Cts_Db_Table_Abstract>
*/
class DealersViewDealers extends Cts_Db_Table_Abstract {

	/* Group: Instance Variables */

	/*
		Variable: $_name
	*/
	protected $_name = 'dealers_vw_dealers';

	/*
		Variable: $_primary
	*/
	protected $_primary = 'id';

	/* Group: Instance Methods */

	/*
		Function: get
	*/
	function get($dealer_id) {
		$tmp_dealer = $this->fetchAll($this->select()->where("id = ?", $dealer_id));
		if (!is_null($tmp_dealer) && count($tmp_dealer) > 0) {
			$tmp_dealer = $tmp_dealer->toArray();
			return $tmp_dealer[0];
		} else {
			return array();
		}
	}

	/*
		Function: getAll

		Returns: array of dealers or an empty array
	*/
	function getAll() {
		$tmp_dealers = $this->fetchAll();
		if (!is_null($tmp_dealers)) {
			return $tmp_dealers->toArray();
		} else {
			return array();
		}
	}

	/*
		Function: getByKeywords

		Arguments:
			keywords - A space-delimited list (string) of words to search for.

		Returns: array of dealers or an empty array
	*/
	function getByKeywords($keywords) {
		$keywords = split(" ", $keywords);
		$where = "1 = 1";
		foreach ($keywords as $word) {
			$where .= $this->getAdapter()->quoteInto(' and (name like ? or code like ? or short_description like ?)', "%".$word."%");
		}
		$tmp_dealers = $this->fetchAll($where);
		if (!is_null($tmp_dealers)) {
			return $tmp_dealers->toArray();
		} else {
			return array();
		}
	}

	/*
		Function: getByAdminFilter
	*/
	function getByAdminFilter($country_code, $dealer_type_id) {
		$where = "1 = 1";
		if (!is_null($country_code) && trim($country_code) != "") {
			$where .= $this->getAdapter()->quoteInto(" and (country_code = ?", $country_code);
			$where .= $this->getAdapter()->quoteInto(" or id in "
				."(select dealer_id from dealers_dealers_countries where country_code = ?))", $country_code);
		}
		if (!is_null($dealer_type_id) && trim($dealer_type_id) != "") {
			$where .= $this->getAdapter()->quoteInto(" and dealer_type_id = ?", $dealer_type_id);
		}
		try {
			$tmp_dealers = $this->fetchAll($where);
		} catch (Exception $e) {
			dd($e);
		}
		if (!is_null($tmp_dealers)) {
			return $tmp_dealers->toArray();
		} else {
			return array();
		}
	}

	/*
		Function: getWhereClauseByKeywords
			Returns a where clause string based on a string containing search keywords.

		Arguments:
			keywords - A space-delimited list (string) of words to search for.

		Returns: string
	*/
	function getWhereClauseByKeywords($keywords) {
		$keywords = split(" ", $keywords);
		$where = "1 = 1";
		foreach ($keywords as $word) {
			$where .= $this->getAdapter()->quoteInto(' and (name like ? or code like ? or short_description like ?)', "%".$word."%");
		}
		return $where;
	}

	/*
		Function: getWhereClauseByAdminFilter
	*/
	function getWhereClauseByAdminFilter($country_code, $dealer_type_id) {
		$where = "1 = 1";
		if (!is_null($country_code) && trim($country_code) != "") {
			$where .= $this->getAdapter()->quoteInto(" and (country_code = ?", $country_code);
			$where .= $this->getAdapter()->quoteInto(" or id in "
				."(select dealer_id from dealers_dealers_countries where country_code = ?))", $country_code);
		}
		if (!is_null($dealer_type_id) && trim($dealer_type_id) != "") {
			$where .= $this->getAdapter()->quoteInto(" and dealer_type_id = ?", $dealer_type_id);
		}
		return $where;
	}

	function getWithinRadius($lat,$lon,$rad,$count = null,$offset = 0,$geartypes = null){

		$R = 6371;  // earth's radius, km
		  
		// first-cut bounding box (in degrees)
		$maxLat = $lat + rad2deg($rad/$R);
		$minLat = $lat - rad2deg($rad/$R);
		// compensate for degrees longitude getting smaller with increasing latitude
		$maxLon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
		$minLon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));

		// convert origin of filter circle to radians
		$lat = deg2rad($lat);
		$lon = deg2rad($lon);
		/*
		$sql = "Select *, acos(sin(".$lat.")*sin(radians(latitude)) + cos(".$lat.")*cos(radians(latitude))*cos(radians(longitude)-".$lon."))*".$R
			." As D	From ( Select *	From ".$this->_name
			." Where latitude > ".$minLat." And latitude < ".$maxLat 
			." And longitude > ".$minLon." And longitude < " . $maxLon 
			." ) As FirstCut Where acos(sin(".$lat.")*sin(radians(latitude)) + cos(".$lat.")*cos(radians(latitude))*cos(radians(longitude)-".$lon."))*".$R." < ".$rad
			." Order by D";
		
		*/
		$select = $this->getAdapter()->select();
		
		if(is_array($geartypes)){
			$gear_select = $this->getAdapter()->select();			
			foreach($geartypes as $geartype){
				$gear_select->orWhere("dealer_category_id = ?",$geartype);
			}
			$gear_select->from(array('dc' => 'dealers_dealers_categories'),
                    array('dealer_id'));
            $gear_subselect = $gear_select->assemble();
            //dd($gear_subselect);
            $select->where(" id in (".$gear_subselect.") ");        			
		}

		$subselect = $this->getAdapter()->select();	
		$subselect->from($this->_name);			
		$subselect->where("latitude > ".$minLat);
		$subselect->where("latitude < ".$maxLat);
		$subselect->where("longitude > ".$minLon);
		$subselect->where("longitude < " . $maxLon);		

		$subselect_sql = "(".$subselect->assemble().") as `FirstCut`";		
		$select_cols = "*, acos(sin(".$lat.")*sin(radians(latitude)) + cos(".$lat.")*cos(radians(latitude))*cos(radians(longitude)-".$lon."))*".$R." As D ";	 
		
		$final = " acos(sin(".$lat.")*sin(radians(latitude)) + cos(".$lat.")*cos(radians(latitude))*cos(radians(longitude)-".$lon."))*".$R." < ".$rad." Order by D";
		
		$additionalwhere = implode($select->getPart('where'));
		if(!empty($additionalwhere)){
			$additionalwhere .= " and ";
		}
		
		$query = "select " . $select_cols . " from " . $subselect_sql . " where " . $additionalwhere . $final;	

		if(!is_null($count)){
			$query .= " limit ".$offset.",".$count;
		}	
		
		return $this->getAdapter()->fetchAll($query);
	}


}
